package com.example.mideaoem.api;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;

import android.util.Base64;
import android.util.Log;

import com.example.mideaoem.api.handler.MessageManagerHandler;
import com.example.mideaoem.api.handler.SecurityHandle;
import com.example.mideaoem.data.FactoryDataBody;
import com.example.mideaoem.model.AppInfo;
import com.example.mideaoem.utils.DateUtil;

public class FormGenerator {

	String format = "2";
	String PC_CLIENT = "0";
	String ANDROID_CLIENT = "1";
	String IOS_CLIENT = "2";
	SecurityHandle builder;
	
	
	private FormGenerator(SecurityHandle handle, String ClientType){
		this.builder = handle;
		ANDROID_CLIENT = ClientType;
	}
	
	private FormGenerator(SecurityHandle handle){
		this.builder = handle;
	}
	
	private static FormGenerator instance;
	public static FormGenerator getInstance(SecurityHandle handle){
		if(instance == null){
			instance = new FormGenerator(handle);
		}
		return instance;
	}
	
	public static FormGenerator getInstance(SecurityHandle handle, String ClientType){
		if(instance == null){
			instance = new FormGenerator(handle, ClientType);
		}
		return instance;
	}
	
	private Map<String, String> addSign(Map<String, String> map, int type) {
		// TODO Auto-generated method stub
		map.put("language", "en_US");
		try {
			map.put("sign", builder.RequestSign(BaseAPI.server_url, BaseAPI.map.get(type), map, BaseAPI.appKey));
		} catch (SecurityException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return map;
	}
	
	private String addSign_app2Base(Map<String, String> map, String uri) {
		// TODO Auto-generated method stub
		String result = "";
		try {
			map.put("serviceUrl", uri);
			result = "&sign="+builder.RequestSign(BaseAPI.server_url, BaseAPI.map.get(BaseAPI.APP2BASE), map, BaseAPI.appKey);
			map.remove("serviceUrl");
		} catch (SecurityException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	return result;
	}
	
	
	private String decodeMap(Map<String, String> map){
		StringBuilder sb = new StringBuilder();
		for (Entry<String, String> entry : map.entrySet()) {
	        String key = entry.getKey().toString();;
	        String value = entry.getValue();
	        sb.append(key+"=");
	        sb.append(value+"&");
	    }
		String result = sb.toString().substring(0, sb.toString().length()-1);
		return result;
	}
	
	/**
	 * 判断邮箱是否已经注册
	 * @param email
	 * @param type
	 * @return
	 */
	public String CheckEmailAvailableRequest(String emailAddr, int type){
		Map<String,String> map = new HashMap<String, String>();
		map.put("appId", BaseAPI.appId);
		map.put("format", format);
		map.put("stamp", DateUtil.getTimeStamp());
		map.put("email", emailAddr);
		map = addSign(map, type);
		return decodeMap(map);
	}
	
	/**
	 * 用户通过邮箱注册
	 * @param emailAddr
	 * @param password
	 * @param type
	 * @return
	 */
	public String UserRegisterRequest(String emailAddr, String password, int type){
		Map<String,String> map = new HashMap<String, String>();
		map.put("appId", BaseAPI.appId);
		map.put("format", format);
		map.put("stamp", DateUtil.getTimeStamp());
		map.put("email", emailAddr);
		try {
			map.put("password", builder.registerEncrypt(password));
		} catch (SecurityException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		map = addSign(map, type);
		return decodeMap(map);
	}
	
	/**
	 * 获取登陆ID
	 * @param emailAddr
	 * @param type
	 * @return
	 */
	public String getLoginIDRequest(String emailAddr, int type){
		Map<String,String> map = new HashMap<String, String>();
		map.put("appId",BaseAPI.appId);
		map.put("clientType", ANDROID_CLIENT);
		map.put("src", BaseAPI.src);
		map.put("format", format);
		map.put("stamp", DateUtil.getTimeStamp());
		map.put("loginAccount", emailAddr);
		map = addSign(map, type);
		return decodeMap(map);
	}
	
	public String userModifyInfo(String sessionId, String nickName, int type){
		Map<String, String> map = new HashMap<String, String>();
		map.put("src", BaseAPI.src);
		map.put("sessionId", sessionId);
		map.put("format", format);
		map.put("stamp", DateUtil.getTimeStamp());
		map.put("nickname", nickName);
		map = addSign(map, type);
		return decodeMap(map);
	}
	
	
	public String deviceModifyInfo(String applianceId, String sessionId, String applianceName, String applianceDes, int type){
		Map<String, String> map = new HashMap<String, String>();
		map.put("src", BaseAPI.src);
		map.put("sessionId", sessionId);
		map.put("format", format);
		map.put("stamp", DateUtil.getTimeStamp());
		map.put("applianceId", applianceId);
		map.put("applianceName", applianceName);
		map.put("applianceDes", applianceDes);
		map = addSign(map, type);
		return sortParams(decodeMap(map));
		
	}
	
	
	/**
	 * 发送激活邮件
	 * @param email
	 * @param type
	 * @return
	 */
	public String sendActiveEmail(String email, int type){
		Map<String, String> map = new HashMap<String, String>();
		map.put("appId", BaseAPI.appId);
		map.put("format", format);
		map.put("stamp", DateUtil.getTimeStamp());
		map.put("email", email);
		map = addSign(map, type);
		return sortParams(decodeMap(map));
	}
	
	/**
	 * 用户登陆
	 * @param emailAddr
	 * @param password
	 * @param type
	 * @return
	 */
	public String userLoginRequest(String emailAddr, String password, String loginId, int type, String pushToken){
		Map<String,String> map = new HashMap<String, String>();
		map.put("appId", BaseAPI.appId);
		map.put("clientType", ANDROID_CLIENT);
		map.put("src", BaseAPI.src);
		map.put("format", format);
		map.put("stamp", DateUtil.getTimeStamp());
		map.put("loginAccount", emailAddr);
		if(!pushToken.equals("")){
			map.put("pushToken", pushToken);
		}
		try {
			map.put("password", builder.loginEncrypt(password, loginId, BaseAPI.appKey));
		} catch (SecurityException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		map = addSign(map, type);
		return decodeMap(map);
	}
	
	/**
	 * 用户登出
	 * @param sessionId
	 * @param type
	 * @return
	 */
	public String userLogoutRequest(String sessionId, int type){
		Map<String,String> map = new HashMap<String, String>();
		map.put("src", BaseAPI.src);
		map.put("sessionId", sessionId);
		map.put("format", format);
		map.put("stamp", DateUtil.getTimeStamp());
		map = addSign(map, type);
		return decodeMap(map);
	}
	
	/**
	 * 获取用户详细信息
	 * @param sessionId
	 * @param type
	 * @return
	 */
	public String getUserInfoRequest(String sessionId, int type){
		Map<String,String> map = new HashMap<String, String>();
		map.put("src", BaseAPI.src);
		map.put("sessionId", sessionId);
		map.put("format", format);
		map.put("stamp", DateUtil.getTimeStamp());
		map = addSign(map, type);
		return decodeMap(map);
	}
	
	/**
	 * 修改密码
	 * @param sessionId
	 * @param oldPassword
	 * @param newPassword
	 * @param type
	 * @return
	 */
	public String modufyPassword(String sessionId, String accessToken, String oldPassword, String newPassword, int type){
		Map<String,String> map = new HashMap<String, String>();
		map.put("src", BaseAPI.src);
		map.put("sessionId", sessionId);
		map.put("format", format);
		map.put("stamp", DateUtil.getTimeStamp());
		try {
			map.put("oldPassword", builder.Encrypt(builder.registerEncrypt(oldPassword), BaseAPI.appKey, accessToken));
			map.put("newPassword", builder.Encrypt(builder.registerEncrypt(newPassword), BaseAPI.appKey, accessToken));
		} catch (SecurityException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		Log.d("rawData","oldPd :"+oldPassword+"  newPd :"+newPassword);
		
		map = addSign(map, type);
		return decodeMap(map);
	}
	
	/**
	 * 重置密码 
	 * @param emailAddr
	 * @param type
	 * @return
	 */
	public String resetPassword(String emailAddr, int type){
		Map<String,String> map = new HashMap<String, String>();
		map.put("appId", BaseAPI.appId);
		map.put("src", BaseAPI.src);
		map.put("format", format);
		map.put("stamp", DateUtil.getTimeStamp());
		map.put("loginAccount", emailAddr);
		map = addSign(map, type);
		return decodeMap(map);
	}
	
	/**
	 * 获取家庭列表
	 * @param sessionId
	 * @param type
	 * @return
	 */
	public String getHomeListRequest(String sessionId, int type){
		Map<String,String> map = new HashMap<String, String>();
		map.put("src", BaseAPI.src);
		map.put("sessionId", sessionId);
		map.put("format", format);
		map.put("stamp", DateUtil.getTimeStamp());
		map = addSign(map, type);
		return decodeMap(map);
	}
	
	/**
	 * 创建家庭
	 * @param sessionId
	 * @param name
	 * @param des
	 * @param address
	 * @param coordinate
	 * @param type
	 * @return
	 */
	public String createFamilyRequest(String sessionId, String name, String des, String address, int type){
		Map<String,String> map = new HashMap<String, String>();
		map.put("src", BaseAPI.src);
		map.put("sessionId", sessionId);
		map.put("format", format);
		map.put("stamp", DateUtil.getTimeStamp());
		map.put("name", name);
		map.put("des", des);
		map.put("address", address);
		map = addSign(map, type);
		return decodeMap(map);
	}
	
	/**
	 * 注销家庭
	 * @param sessionId
	 * @param homegroupId
	 * @param type
	 * @return
	 */
//	public String deleteHome(String sessionId, String homegroupId, int type){
//		Map<String,String> map = new HashMap<String, String>();
//		map.put("src", BaseAPI.src);
//		map.put("sessionId", sessionId);
//		map.put("format", format);
//		map.put("stamp", DateUtil.getTimeStamp());
//		map.put("homegroupId", homegroupId);
//		map = addSign(map, type);
//		return decodeMap(map);
//	}
	
	/**
	 * 获取家庭下的设备列表
	 * @param sessionId
	 * @param homegroupId
	 * @param type
	 * @return
	 */
	public String getApplianceListRequest(String sessionId, String homegroupId, int type){
		Map<String,String> map = new HashMap<String, String>();
		map.put("src", BaseAPI.src);
		map.put("sessionId", sessionId);
		map.put("format", format);
		map.put("stamp", DateUtil.getTimeStamp());
		map.put("homegroupId",homegroupId);
		map = addSign(map, type);
		return decodeMap(map);
	}
	
	/**
	 * 激活家电
	 * @param sessionId
	 * @param applianceSn
	 * @param referSn
	 * @param homegroupId
	 * @param applianceName
	 * @param applianceType
	 * @param type
	 * @return
	 */
	public String activeApplianceRequest(String sessionId, String accessToken, String applianceSn, String referSn, String homegroupId, String applianceName, String applianceType, int type){
		Map<String,String> map = new HashMap<String, String>();
		map.put("src", BaseAPI.src);
		map.put("sessionId", sessionId);
		map.put("format", format);
		map.put("stamp", DateUtil.getTimeStamp());
		try {
			map.put("applianceSn", builder.Encrypt(applianceSn, BaseAPI.appKey, accessToken));
			map.put("referSn", builder.Encrypt(referSn, BaseAPI.appKey, accessToken));
		} catch (SecurityException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		map.put("homegroupId", homegroupId);
		map.put("applianceName", applianceName);
		map.put("applianceType", applianceType);
		map = addSign(map, type);
		return decodeMap(map);
	}
	
	/**
	 * 删除家电
	 * @param sessionId
	 * @param applianceId
	 * @param type
	 * @return
	 */
	public String deleteAppianceRequest(String sessionId, String applianceId, int type){
		Map<String,String> map = new HashMap<String, String>();
		map.put("src", BaseAPI.src);
		map.put("sessionId", sessionId);
		map.put("format", format);
		map.put("applianceId", applianceId);
		map.put("stamp", DateUtil.getTimeStamp());
		map = addSign(map, type);
		return decodeMap(map);
	}
	
	/**
	 * 家电透传
	 * @param sessionId
	 * @param applianceId
	 * @param funId
	 * @param order
	 * @param type
	 * @return
	 */
	public String applianceSendRequest(String sessionId, String accessToken, String applianceId, String funId, byte[] order, int type, MessageManagerHandler manager){
		Log.i("rawData", "send--->   "+FactoryDataBody.printHexString(order));
		Map<String,String> map = new HashMap<String, String>();
		map.put("src", BaseAPI.src);
		map.put("sessionId", sessionId);
		map.put("format",format);
		map.put("stamp", DateUtil.getTimeStamp());
		map.put("applianceId", applianceId);
		map.put("funId",funId);
		map.put("order",manager.encryptString(order, applianceId, accessToken));
		map = addSign(map, type);
		return decodeMap(map);
	}
	
	/**
	 * 刷新pushToken
	 * @param sessionId
	 * @param token
	 * @param type
	 * @return
	 */
	public String refreshToken(String sessionId, String token, int type){
		Map<String,String> map = new HashMap<String, String>();
		map.put("src", BaseAPI.src);
		map.put("sessionId", sessionId);
		map.put("format", format);
		map.put("stamp", DateUtil.getTimeStamp());
		map.put("pushToken", token);
		map = addSign(map, type);
		return decodeMap(map);
	}
	
	/**
	 * 刷新用户Session
	 * @param sessionId
	 * @param type
	 * @return
	 */
	public String refreshSession(String sessionId, int type){
		Map<String,String> map = new HashMap<String, String>();
		map.put("src", BaseAPI.src);
		map.put("sessionId", sessionId);
		map.put("format", format);
		map.put("stamp", DateUtil.getTimeStamp());
		map = addSign(map, type);
		return decodeMap(map);
	}
	
	/**
	 * 获取设备信息
	 * @return
	 */
	public String getDeviceInfo(){
		String result = "";
		return null;
	}
	
	
	
	public String app2baseTranmit(String sessionId, String accessToken, String data, int uri){
		Map<String,String> map = new HashMap<String, String>();
		map.put("src", BaseAPI.src);
		map.put("sessionId", sessionId);
		map.put("data", builder.Encrypt(data, BaseAPI.appKey, accessToken));
		map.put("stamp", DateUtil.getTimeStamp());
		map.put("proType", "0x01");
		map.put("language", "en_US");
		String result = sortParams(decodeMap(map));
		String sign = addSign_app2Base(map, BaseAPI.map.get(uri));
		Log.i("postToAppServer","url = "+BaseAPI.map.get(uri)+ "  json = "+data);
		return result+sign;
	}	
	
	
	
	/**
	 * 请求参数排序
	 *
	 * @param param
	 * @return
	 */
	protected String sortParams(String param) {
		// String retString = "";
		StringBuffer buffer = new StringBuffer();
		String[] ArrParam = param.split("&");
		Arrays.sort(ArrParam);
		for (int index = 0; index < ArrParam.length; index++) {
			// retString += ArrParam[index] + "&";
			buffer.append(ArrParam[index] + "&");
		}
		String retString = buffer.toString();
		retString = retString.substring(0, retString.length() - 1);
		return retString;
	}
	
	/**
	 * 获取更新信息
	 * @param type
	 * @return
	 */
	public String app_checkforupdate(int type){
		Map<String,String> map = new HashMap<String, String>();
		map.put("appId", BaseAPI.appId);
		map.put("format", format);
		map.put("clientType", ANDROID_CLIENT);
		map.put("appType", "0x10");
		map.put("stamp", DateUtil.getTimeStamp());
		map = addSign(map, type);
		return decodeMap(map);
	}
	
	/**
	 * 更新App
	 * @param type
	 * @return
	 */
	public String app_update(String versionCode, int type){
		Map<String,String> map = new HashMap<String, String>();
		map.put("appId", BaseAPI.appId);
		map.put("format", format);
		map.put("clientType", ANDROID_CLIENT);
		map.put("appType", "0x10");
		map.put("stamp", DateUtil.getTimeStamp());
		map.put("versionCode", versionCode);
		map = addSign(map, type);
		return decodeMap(map);
	}
	
	//头像
	public Map<String, String> user_icon(String SessionId, int type){
		Map<String, String> map = new HashMap<String, String>();
		map.put("src", BaseAPI.src);
		map.put("sessionId", SessionId);
		map.put("format", format);
		map.put("stamp", DateUtil.getTimeStamp());
		map = addSign(map, type);
		return map;
	}
	
	
}
